export function getLocal<T>(key: string, defaultValue: T): T {
  try {
    const str = localStorage.getItem(key);
    if (str) {
      const value = JSON.parse(str);
      if (value) {
        return value;
      } else {
        return defaultValue;
      }
    } else {
      return defaultValue;
    }
  } catch (error) {
    return defaultValue;
  }
}

export function setLocal(key: string, value: object) {
  localStorage.setItem(key, JSON.stringify(value));
}
export function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

export function getToken() {
  return localStorage.getItem('token');
}

export function setToken(token: string) {
  localStorage.setItem('token', token);
}

export function copyText(value: string) {
  // 创建元素用于复制
  const aux = document.createElement('input');
  // 设置元素内容
  aux.setAttribute('value', value);
  // 将元素插入页面进行调用
  document.body.appendChild(aux);
  // 复制内容
  aux.select();
  // 将内容复制到剪贴板
  document.execCommand('copy');
  // 删除创建元素
  document.body.removeChild(aux);
}

export function getRandom32() {
  let str_nums = '';
  const range = 32;
  const arr = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
  ];
  for (let i = 0; i < range; i++) {
    const id = Math.round(Math.random() * (arr.length - 1));
    str_nums += arr[id];
  }
  return str_nums;
}
